package com.yu.service.impl;

import com.alibaba.fastjson.JSON;
import com.yu.dao.EmpMapper;
import com.yu.pojo.Emp;
import com.yu.pojo.Result;
import com.yu.pojo.vo.EmpVo;
import com.yu.service.EmpService;
import com.yu.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;

    @Override
    public String findByPage(EmpVo empVo) {
        int page = (empVo.getPage()-1) * empVo.getPageSize();
        empVo.setPage(page);
        List<Emp> emps = empMapper.findByPage(empVo);

        int row = empMapper.findCount(empVo);

        Map<String,Object> map = new HashMap<>();
        map.put("total",row);
        map.put("rows",emps);

        Result result = Result.success(map);
        return JSON.toJSONString(result);
    }

    @Override
    public String deleteByIds(List<Integer> ids) {
        int row = empMapper.deleteByIds(ids);
        Result success = Result.success();
        return JSON.toJSONString(success);
    }

    @Override
    public String addEmp(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");
        int row = empMapper.insertEmp(emp);
        Result success = Result.success();
        return JSON.toJSONString(success);
    }

    @Override
    public String findEmpById(Integer id) {
        Emp emp = empMapper.findById(id);
        Result success = Result.success(emp);
        return JSON.toJSONString(success);
    }

    @Override
    public String updateEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        int row = empMapper.updateEmp(emp);

        Result success = Result.success();
        return JSON.toJSONString(success);
    }

    @Override
    public String login(Emp emp) {
        Emp newEmp = empMapper.getByUsernameAndPassword(emp);
        Result result = new Result();
        if (newEmp != null){
            Map<String,Object> map = new HashMap<>();
            map.put("id",newEmp.getId());
            map.put("username",newEmp.getUsername());
            map.put("password",newEmp.getPassword());

            String jwt = JwtUtils.generateJwt(map);
            result = Result.success(jwt);
        }else if (newEmp == null){
            result = Result.error("用户名或密码错误");
        }
        return JSON.toJSONString(result);
    }
}
